package com.atguigu.gulimail.member.web.intercept;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {


    public static ThreadLocal<MemberResponseVo> threadLocal=new ThreadLocal<>();

    /**
     * 配置拦截订单服务的所有请求,在所有请求之前检查用户是否登录
     * 登录: 放行
     * 未登录:跳转到登陆页面
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri=request.getRequestURI();
        boolean match=new AntPathMatcher().match("/member/**",uri);
        if(match){
            return true;
        }


        MemberResponseVo member = (MemberResponseVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if(member!=null){
            threadLocal.set(member);
            return true;
        }else {
            request.getSession().setAttribute("msg","请登录");
            response.sendRedirect("http://auth.gulimail.com/login.html");
            return false;
        }

    }


}
